package com.mgm.click.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.mgm.advertisement.service.AdvertisementService;
import com.mgm.click.service.ClickInfoService;
import com.mgm.constant.GobalConstant;
import com.mgm.dao.AffsettingsMapper;
import com.mgm.dao.ClickInfoMapper;
import com.mgm.dto.AffsettingsForClickDto;
import com.mgm.pojo.ClickInfo;
import com.mgm.pojo.ClickInfoExample;
import com.mgm.pojo.ClickInfoExample.Criteria;
import com.mgm.utils.NumberArithmeticUtils;
import com.mgm.utils.RandomCodeUtils;

@Service
public class ClickInfoServiceImpl implements ClickInfoService {
	
	private static Logger logger =LoggerFactory.getLogger(ClickInfoServiceImpl.class);
	
	@Autowired
	private ClickInfoMapper clickInfoMapper;
	@Autowired
	private AffsettingsMapper affsettingsMapper;
	@Autowired
	private AdvertisementService advertisementService;

	@Override
	public void saveClickInfo(Map<String, String> map) {
		ClickInfo clickInfo = mapToClickInfo(map);
		boolean isNull = isParamNull(map);
		if(isNull) { //参数为空，直接入库
			clickInfo.setCode(GobalConstant.CLICK_LACK_PARAMS+""); //缺少参数
		} else if(!StringUtils.isEmpty(clickInfo.getOfferid()) && !StringUtils.isEmpty(clickInfo.getAffid())) { //渠道
			AffsettingsForClickDto affsettingsForClickDto = affsettingsMapper.selectByAffIdAndOfferId(clickInfo.getAffid(), clickInfo.getOfferid());
			if(affsettingsForClickDto!=null) {
				clickInfo.setOffername(affsettingsForClickDto.getOfferName());
				clickInfo.setPayType(affsettingsForClickDto.getPay_type());
				clickInfo.setPayPrice(affsettingsForClickDto.getPay_price()); //单价
				if(affsettingsForClickDto.getAffoffer_premium() != null) {
					clickInfo.setAffPayout(affsettingsForClickDto.getAffoffer_premium_price());
				} else if (affsettingsForClickDto.getOffer_premium() != null) {
					clickInfo.setAffPayout(affsettingsForClickDto.getOffer_premium_price());
				} else if (affsettingsForClickDto.getAdv_premium() != null) {
					BigDecimal premiumPercent = NumberArithmeticUtils.safeDivide(affsettingsForClickDto.getAdv_premium(), GobalConstant.PERCENT); //溢价/100
					clickInfo.setAffPayout(NumberArithmeticUtils.safeMultiply(premiumPercent, affsettingsForClickDto.getPay_price())); //溢价后单价
				} else {
					clickInfo.setAffPayout(affsettingsForClickDto.getPay_price());
				}
				if(!affsettingsForClickDto.getEnabled()) { //渠道开启
					clickInfo.setCode(GobalConstant.CLICK_AFF_CLOSE+""); 
				}
			} else {
				clickInfo.setCode(GobalConstant.CLICK_PARAMS_ERROR+"");
			}
		} else {
			clickInfo.setCode(GobalConstant.CLICK_SUCCESS+"");
		}
		String tid = System.currentTimeMillis()+clickInfo.getAffid().substring(GobalConstant.AFF_PRE.length())+RandomCodeUtils.randomNumeric(4); //系统生成Tid
		clickInfo.setTid(tid); //MGM的tid
		clickInfoMapper.insertSelective(clickInfo); //入库
		logger.info("【Click Info into db】 data is {}", clickInfo.toString());
	}

	/**
	 * 判断下游参数是否有未传的.
	 * @Title: isParamNull   
	 * @Description: TODO(...)   
	 * @param: @param map
	 * @param: @return      
	 * @return: boolean      
	 * @throws
	 */
	private boolean isParamNull(Map<String, String> map) {
		if(StringUtils.isEmpty(map.get("offid"))) return true;
		if(StringUtils.isEmpty(map.get("affid"))) return true;
		if(StringUtils.isEmpty(map.get("tid"))) return true;
		if(StringUtils.isEmpty(map.get("subaffid"))) return true;
		if(StringUtils.isEmpty(map.get("ip"))) return true;
		if(StringUtils.isEmpty(map.get("userAgent"))) return true;
		
		return false;
	}
	
	/**
	 * 判断下游参数是否有缺省的.
	 * @Title: isParamNull   
	 * @Description: TODO(...)   
	 * @param: @param clickInfo
	 * @param: @return      
	 * @return: boolean      
	 * @throws
	 */
	private boolean isParamNull(ClickInfo clickInfo) {
		if(StringUtils.isEmpty(clickInfo.getOfferid())) return true;
		if(StringUtils.isEmpty(clickInfo.getAffid())) return true;
		if(StringUtils.isEmpty(clickInfo.getAfftid())) return true;
//		if(StringUtils.isEmpty(clickInfo.getSubaffid())) return true;
		if(StringUtils.isEmpty(clickInfo.getIp())) return true;
		if(StringUtils.isEmpty(clickInfo.getUserAngent())) return true;
		
		return false;
	}

	private ClickInfo mapToClickInfo(Map<String, String> map) {
		Date curTime = new Date(); 
		
		ClickInfo clickInfo = new ClickInfo();
		clickInfo.setClickat(curTime); //当前时间
		
		clickInfo.setOfferid(map.get("offid"));
		clickInfo.setAffid(map.get("affid"));
		clickInfo.setPkgname(map.get("pkgname"));
		clickInfo.setAfftid(map.get("tid")); //这存渠道tid, tid存的是MGM tid
		clickInfo.setSubaffid(map.get("subaffid"));
		
		clickInfo.setIp(map.get("ip"));
		clickInfo.setRefer(map.get("refer"));
		clickInfo.setUserAngent(map.get("user_agent"));
		
		clickInfo.setIdfa(map.get("idfa"));
		clickInfo.setGaid(map.get("gaid"));
		clickInfo.setAid(map.get("aid"));
		
		clickInfo.setCode(GobalConstant.CLICK_SUCCESS+""); //默认成功
		
		return clickInfo;
	}

	@Override
	public int saveClickInfo(ClickInfo clickInfo) {
		boolean isNull = isParamNull(clickInfo);
		if(isNull) { //参数为空，直接入库
			clickInfo.setCode(GobalConstant.CLICK_LACK_PARAMS+""); //缺少参数
		} else if(!StringUtils.isEmpty(clickInfo.getOfferid()) && !StringUtils.isEmpty(clickInfo.getAffid())) { //渠道
			AffsettingsForClickDto affsettingsForClickDto = affsettingsMapper.selectByAffIdAndOfferId(clickInfo.getAffid(), clickInfo.getOfferid());
			if(affsettingsForClickDto!=null) {
				clickInfo.setP1(affsettingsForClickDto.getOriginOfferId()); //上游offerid
				clickInfo.setOffername(affsettingsForClickDto.getOfferName());
				clickInfo.setPayType(affsettingsForClickDto.getPay_type());
				clickInfo.setPayPrice(affsettingsForClickDto.getPay_price()); //单价
				//--------可优化-start--------------
				if(affsettingsForClickDto.getAffoffer_premium() != null) { //渠道有溢价的情况
					clickInfo.setAffPayout(affsettingsForClickDto.getAffoffer_premium_price());
				} else if (affsettingsForClickDto.getOffer_premium() != null) { //广告有溢价
					clickInfo.setAffPayout(affsettingsForClickDto.getOffer_premium_price());
				} else if (affsettingsForClickDto.getAdv_premium() != null) { //广告主有溢价
					BigDecimal premiumPercent = NumberArithmeticUtils.safeDivide(affsettingsForClickDto.getAdv_premium(), GobalConstant.PERCENT); //溢价/100
					clickInfo.setAffPayout(NumberArithmeticUtils.safeMultiply(premiumPercent, affsettingsForClickDto.getPay_price())); //溢价后单价
				} else {
					clickInfo.setAffPayout(affsettingsForClickDto.getPay_price());
				}
				//--------可优化-end--------------
				if(!affsettingsForClickDto.getEnabled()) { //渠道开启
					clickInfo.setCode(GobalConstant.CLICK_AFF_CLOSE+""); 
				}
				
			} else {
				clickInfo.setCode(GobalConstant.CLICK_PARAMS_ERROR+"");
			}
		} else {
			clickInfo.setCode(GobalConstant.CLICK_SUCCESS+"");
		}
		
		logger.info("【Click Info into db】 data is {}", clickInfo.toString());
		return clickInfoMapper.insertSelective(clickInfo); //入库
	}

	@Override
	public ClickInfo findByTid(String tid) {
		ClickInfoExample example = new ClickInfoExample();
		Criteria criteria = example.createCriteria();
		criteria.andTidEqualTo(tid);
		List<ClickInfo> list = clickInfoMapper.selectByExample(example);
		if(!CollectionUtils.isEmpty(list)) {
			return list.get(0);
		}
		
		return null;
	}
}
